package com.fengwuj.mutils.thread;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * 修订记录：
 * jiangbo 2020/1/7 19:11 创建
 *
 * @author jiangbo
 */
@Slf4j
public class ExecutorUtils {
    private static final int THREAD_NUMBER = 30;

    private static ExecutorService executorService = Executors.newFixedThreadPool(THREAD_NUMBER);

    /**
     * 执行单个任务
     * @param callable
     * @param <V>
     * @return
     */
    public static <V> V execute(Callable<V> callable) throws ExecutionException, InterruptedException {
        if(callable!=null){
            List<Callable<V>> list = new ArrayList<>();
            list.add(callable);
            List<V> result = execute(list);
            if(null != result && !CollectionUtils.isEmpty(result)){
                return result.get(0);
            }
            return null;
        }else{
            return null;
        }
    }


    /**
     * 执行一系列任务
     *
     * @param callableList
     * @param <V>
     * @return
     */
    public static <V> List<V> execute(List<Callable<V>> callableList) throws InterruptedException
            , ExecutionException {
        if (!CollectionUtils.isEmpty(callableList)) {
            List<V> result = new ArrayList<>();
            List<Future<V>> futures = executorService.invokeAll(callableList);
            if (!CollectionUtils.isEmpty(futures)) {
                for (Future<V> future : futures) {
                    result.add(future.get());
                }
            }
            return result;
        } else {
            return null;
        }
    }

    /**
     * 异步处理
     * @param runnable
     */
    public static void executeAsync(Runnable runnable){
        executorService.execute(runnable);
    }
}
